const hx = require("hbuilderx");
const fs = require('fs')
const {
	setUploadServeDataPath
} = require('../options.js')
const {
	getManifestData
} = require('../utils/hx')
const checkIp = require('../utils/checkIp')


function createFile(filePath, data = {}) {
	fs.writeFileSync(filePath, JSON.stringify(data, null, '\t'), 'utf-8');
}

// 命令：setUploadServe
module.exports = async function(type) {
	const uniAppId = (await getManifestData('appid')) + (type == 'h5' ? 'h5' : '');

	// 表单数据
	const formItems = [{
		type: "input",
		name: "ip",
		label: "IP",
		placeholder: '请输入IP',
		value: "",
		required: true
	}, {
		type: "input",
		name: "root",
		label: "用户名",
		placeholder: '请输入用户名',
		value: "",
		required: true
	}, {
		type: "input",
		name: "pwd",
		label: "密 码",
		placeholder: '请输入密码',
		value: "",
		required: true
	}, {
		type: "input",
		name: "dir",
		label: "目录路径",
		placeholder: '请输入目录路径',
		value: "/apps/deploy/dist/",
		required: true
	}]
	if (type == 'wgt') formItems.push({
		type: "input",
		name: "domain",
		label: "上传后的复制链接前缀",
		placeholder: '请输入上传后的复制链接前缀',
		value: "",
		required: false
	})
	// 默认的表单-value数据
	let initFormData = formItems.reduce((p, c) => {
		p[c.name] = ""
		return p
	}, {})

	// 获取已保存的表单-value数据
	const uploadServeJson = await hx.util.readJSONValue(setUploadServeDataPath, uniAppId)
	if (uploadServeJson.code == '-1') {
		createFile(setUploadServeDataPath)
	} else if (uploadServeJson.data) {
		initFormData = uploadServeJson.data
	}

	try {
		const res = await hx.window.showFormDialog({
			formItems: formItems.map(i => {
				if (initFormData[i.name]) {
					i.value = initFormData[i.name]
				}
				return i
			}),
			title: "设置上传服务器",
			subtitle: "打包成功的wgt将自动上传您在此设置的服务器",
			width: 480,
			submitButtonText: "提交(&S)",
			cancelButtonText: "取消(&C)",
			validate: async function(formData) {
				try {
					const baseRes = formItems.every(i => {
						if (i.required && !formData[i.name]) {
							this.showError(i.placeholder);
							return false
						}
						return true
					})
					if(baseRes) await checkIp(formData)
					return baseRes
				} catch (e) {
					hx.window.showWarningMessage(e);
					return false
				}
			},
		})
		
		hx.util.writeJSONValue(setUploadServeDataPath, uniAppId, res);
	} catch (e) {
		//TODO handle the exception
		if(e == -1) return
		hx.window.showWarningMessage(e.message || e);
	}
}